<?php

declare(strict_types=1);

namespace App\Controller\Home\Drp;

use App\Controller\AbstractController;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Distributors;
use App\Model\Normal;
use App\Model\Station;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\Redis;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;

class HomeStationController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Station $station;


    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Device $device;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**检查充电站是否存在
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function checkStation(RequestInterface $request):ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $address = $request->input('address');
        $station = $this->station->where('address',$address)
            ->where('distributor_id',$info['id'])
            ->first(['id','address','name','images']);
        if($station){
            return $this->success($station);
        }
        return $this->error('1002','暂无该站点');
    }

    /**解绑设备
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function unbindDevice(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $sn = $request->input('sn');
        if(is_string($sn)){
            $sn = trim($sn);
        }
        if(!$sn){
            return $this->error(code:1002,msg:'设备编号不能为空');
        }
        $device = $this->device->where('sn',$sn)->first();
        $device->station_id = 0;
//        if($info['level'] == Distributors::LEVEL_1){
//            if($device->child_distributor_id > 0){
//                return $this->error(code:1002,msg:'当前设备应由子经销商解绑');
//            }
//            $device->distributor_id = 0;
//        }else{
//            $device->child_distributor_id = 0;
//        }
        $device->save();
        return $this->success();
    }

    /**编辑电站
     * @param RequestInterface $request
     * @return ResponseInterface
     */

    public function editStation(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['id','address','station_name','images','lat','lng','siteScene','siteType','fireFacilities',
            'canopyFlag','districtCode']);

        if(isset($params['images']) && $params['images']){
            $params['images'] = json_encode($params['images']);
        }
        try{
            if(isset($params['id']) && $params['id']){
                $station = Station::find($params['id']);
            }else{
                $station = new Station();
            }
            $station->fill($params);
            $station->distributor_id = $info['id'];
            $station->name = $params['station_name'];
            $station->save();
            return $this->success();
        }catch (\Exception $e){
            return $this->error(1001,$e->getMessage());
        }
    }

    public function stationDetail(RequestInterface $request){
        $id = $request->input('id');
        $data = $this->station->where('id',$id)->first();
        return $this->success($data);
    }

    public function delStation(RequestInterface $request){
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $id = $request->input('id');
        if(!$id){
            return $this->error(1001,'缺少参数电站id');
        }
        $check = Device::where('station_id',$id)->count();
        if($check > 0){
            return $this->error(1001,'请先移除电站名下设备');
        }
        Station::where('id',$id)->delete();
        return $this->success();
    }

    public function stationDevice(RequestInterface $request){
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $id = $request->input('id');
        $list = Device::where('station_id',$id)->get();
        return $this->success($list);
    }

    public function batchBind(RequestInterface $request){
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $station_id = $request->input('station_id');
        $devices = $request->input('devices');
        if(!is_array($devices)){
            $devices = json_decode($devices);
        }
        Device::whereIn('id',$devices)->update(['station_id'=>$station_id]);
        return $this->success();
    }

    /**添加设备
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function bindDevice(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['sn','address','station_name','images','lat','lng','siteScene','siteType','fireFacilities',
            'canopyFlag','districtCode']);
        if(!$params['station_name']){
            return $this->error(code:1002,msg:'电站名称不能为空');
        }
        if(!$params['address']){
            return $this->error(code:1002,msg:'地址不能为空');
        }
        if(!$params['lat'] || !$params['lng']){
            return $this->error(code:1002,msg:'经纬度不能为空');
        }
        if(!$params['sn']){
            return $this->error(code:1002,msg:'设备编号不能为空');
        }
        $station =  $this->station->where('address',$params['address'])
            ->where('name',$params['station_name'])
            ->where('distributor_id',$info['id'])
            ->first();
        if(!$station){
            $saveStation['distributor_id'] = $info['id'];
            $saveStation['name'] = $params['station_name'];
            $saveStation['lat'] = $params['lat'];
            $saveStation['lng'] = $params['lng'];
            $saveStation['address'] = $params['address'];
            if($params['images']){
                $saveStation['images'] = json_encode($params['images']);
            }
            if($params['siteScene']){
                $saveStation['siteScene'] = $params['siteScene'];
            }
            if($params['siteType']){
                $saveStation['siteType'] = $params['siteType'];
            }
            if($params['fireFacilities']){
                $saveStation['fireFacilities'] = $params['fireFacilities'];
            }
            if($params['canopyFlag']){
                $saveStation['canopyFlag'] = $params['canopyFlag'];
            }
            if($params['districtCode']){
                $saveStation['districtCode'] = $params['districtCode'];
            }
            $station = Station::create($saveStation);
        }else{
            if($params['images']) {
                $station->images = json_encode($params['images']);
            }
            $station->lng = $params['lng'];
            $station->lat = $params['lat'];
            $station->save();
        }
        if(is_string($params['sn'])){
            $params['sn'] = trim($params['sn']);
        }
        $device = $this->device->where('sn',$params['sn'])->first();
        if(!$device){
            return $this->error('1002','该设备编号不存在');
        }
        if($device->station_id > 0){
            return $this->error('1002','该设备已绑定站点 请先解绑');
        }
        if(!$device){
            return $this->error('1002','设备编号不存在');
        }
        if($info['level'] == Distributors::LEVEL_1){
            if($device->distributor_id > 0 && $device->distributor_id != $info['id']){
                return $this->error(1002,'该设备已绑定其他一级分销商');
            }
            $device->distributor_id = $info['id'];
            $device->child_distributor_id = 0;
        }else{
            $distributor = $this->distributors->where('id',$info['id'])->first();
            if($distributor->parent_id <= 0){
                if($device->distributor_id > 0){
                    $distributor->parent_id = $device->distributor_id;
                    $distributor->save();
                }
            }
            if($device->distributor_id > 0 && $distributor->parent_id > 0 &&  $distributor->parent_id != $device->distributor_id  ){
                return $this->error(1002,'设备归属异常 请联系管理员');
            }
            if($device->child_distributor_id > 0 && $device->child_distributor_id != $info['id']){
                return $this->error(1002,'该设备已绑定其他二级分销商');
            }
            $device->child_distributor_id = $info['id'];
        }
        $charge = ChargeOption::where('distributor_id',0)->orderBy('sort','desc')->first();
        $device->station_id = $station->id;
        if($charge){
            $device->charge_id = $charge->id;
        }
        $device->save();
        return $this->success();
    }

    /**电站列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function list(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $list = $this->station->where('distributor_id',$info['id'])
            ->get();
        return $this->success($list);
    }




}
